package org.hyacinth.common.utils;

import jakarta.mail.MessagingException;
import jakarta.mail.internet.MimeMessage;
import org.springframework.boot.autoconfigure.mail.MailProperties;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;

import java.io.UnsupportedEncodingException;
import java.util.Optional;

public class MailUtils {
    private JavaMailSender javaMailSender;
    private MailProperties mailProperties;

    public MailUtils(JavaMailSender javaMailSender, MailProperties mailProperties) {
        this.javaMailSender = javaMailSender;
        this.mailProperties = mailProperties;
    }

    public void sendMail(String to) throws MessagingException, UnsupportedEncodingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, false);
        String personal = Optional.ofNullable(mailProperties.getProperties()
                        .get("personal"))
                .orElse(mailProperties.getUsername());

        helper.setFrom(mailProperties.getUsername(), personal);
        helper.setTo(to);
        helper.setSubject("邮件发送测试");
        helper.setText("<h1>用户注册成功</h1>", true);

        javaMailSender.send(mimeMessage);
    }

    public void sendMail(String to, String Subject, String Text) throws MessagingException, UnsupportedEncodingException {
        MimeMessage mimeMessage = javaMailSender.createMimeMessage();
        MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, false);
        helper.setFrom("485592830@qq.com", "博客系统");
        helper.setTo(to);
        helper.setSubject(Subject);
        helper.setText(Text, true);

        javaMailSender.send(mimeMessage);
    }
}
